<template>
  <el-dialog append-to-body :title="title" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'560px'">
    <el-form label-width="80px" size="small" :model="memberForm" @submit.native.prevent v-loading="loading">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="text-center">
          <app-uploader title="头像图片" :limit="1" :initFiles="memberForm.avator ? [memberForm.avator] : []" :accept="'image/*'" :fileFormat="fileFormat" @change="handleAvatorOption($event)"></app-uploader>
          <p>头像</p>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="姓名" required>
            <el-input size="small" v-model.trim="memberForm.name" placeholder="请输入姓名" maxlength="20" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="登录账号" required>
            <el-input size="small" v-model.trim="memberForm.username" placeholder="请输入登录账号" maxlength="32" :disabled="!!memberId" show-word-limit></el-input>
            <div class="text-gray" v-if="!memberId">帐号由数字或字母组成，最长不能超过32位</div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="手机号" required>
            <el-input size="small" v-model.trim="memberForm.phone" placeholder="请输入手机号" maxlength="11" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="userType == 0">
          <el-form-item label="所属部门" required>
            <el-cascader size="small" placeholder="请选择所属部门" clearable filterable :options="tree" :props="{ label: 'name', value: 'id', checkStrictly: true }" v-model="memberForm.depart" class="full-width" @change="clearRoles()"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="岗位">
            <el-input size="small" type="textarea" :rows="2" v-model.trim="memberForm.work" placeholder="请输入岗位" maxlength="150" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="是否启用">
            <el-switch v-model="memberForm.status"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-form-item label="权限">
            <div></div>
            <el-button type="text" @click="openPowerModal()">分配权限</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="submitLoading" @click="closeModal()">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="validForm()">保存</el-button>
    </div>

    <power-form :visible.sync="isShowModel" :depart-id="currentDepartId" :userType="userType" :checked="memberForm.power" :name="memberForm.name" @check="getCheckedNodes"></power-form>
  </el-dialog>
</template>

<script>
import Setting from '@/settings';
import AppUploader from '@/components/AppUploader/index';
import PowerForm from '@/views/user-management/components/powerForm';
import { AddUser, UpdateUser, GetUserById } from '@/views/user-management/services/index';
export default {
  props: ['visible', 'title', 'tree', 'memberId', 'userType', 'parentIds'],
  components: {
    AppUploader,
    PowerForm
  },
  data() {
    return {
      memberForm: {
        avator: '',
        name: '',
        username: '',
        phone: '',
        depart: [],
        work: '',
        status: true,
        power: []
      },
      currentDepartId: null,
      isShowModel: false,
      loading: false,
      submitLoading: false,
      fileFormat: ['jpg', 'jpeg', 'png']
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue, oldValue) {
        if (!newValue) return;
        if (this.parentIds && this.parentIds.length) {
          this.memberForm.depart = this.parentIds;
        }
        if (!this.memberId) return;
        this.setForm();
        
      }
    }
  },
  methods: {
    clearRoles() {
      this.memberForm.power = [];
    },
    getCheckedNodes(value) {
      this.memberForm.power = value.map(item => item.id);
    },
    openPowerModal() {
      this.currentDepartId = this.memberForm.depart.length ? this.memberForm.depart[this.memberForm.depart.length - 1] : null;
      this.isShowModel = true;
    },
    // 上传组件回调
    handleAvatorOption(value) {
      if (value && value.length) {
        this.memberForm.avator = value[0].fileUrl;
      } else {
        this.memberForm.avator = '';
      }
    },
    closeModal() {
      this.$emit('update:visible', false);
      this.resetForm();
    },
    validForm() {
      if (!this.memberForm.name) {
        this.$message.warning('请输入姓名!');
        return;
      }
      if (!this.memberForm.username) {
        this.$message.warning('请输入登录账号!');
        return;
      }
      if (!Setting.expression[0].value.test(this.memberForm.username)) {
        this.$message.warning('登录账号只能输入字母和数字!');
        return;
      }
      if (!this.memberForm.phone) {
        this.$message.warning('请输入手机号!');
        return;
      }
      if (this.memberForm.phone && !Setting.expression[1].value.test(this.memberForm.phone)) {
        this.$message.warning('手机号格式不正确!');
        return;
      }
      if (this.userType == 0 && (!this.memberForm.depart || !this.memberForm.depart.length)) {
        this.$message.warning('请选择所属部门!');
        return;
      }
      this.submitLoading = true;
      const queryData = {
        proId: 4,
        userType: this.userType, // 用户类型
        // gender: 1, // 性别 0女1男
        headUrl: this.memberForm.avator,
        name: this.memberForm.name, // 昵称
        username: this.memberForm.username, // 用户名
        phone: this.memberForm.phone, // 电话
        roleIds: this.memberForm.power,
        depId: this.memberForm.depart[this.memberForm.depart.length - 1],
        workDescribe: this.memberForm.work, // 工作描述
        checkStatus: this.memberForm.status ? 0 : 1
      }
      if (!this.memberId) {
        AddUser(queryData)
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success(`${this.title}成功!`);
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error(`${this.title}失败!`);
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      } else {
        UpdateUser({
          ...queryData,
          id: this.memberId
        })
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success(`${this.title}成功!`);
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error(`${this.title}失败!`);
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      }
    },
    resetForm() {
      this.memberForm.avator = '';
      this.memberForm.name = '';
      this.memberForm.username = '';
      this.memberForm.phone = '';
      this.memberForm.depart = [];
      this.memberForm.work = '';
      this.memberForm.status = true;
      this.memberForm.power = [];
    },
    setForm() {
      this.loading = true;
      GetUserById({ id: this.memberId })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.memberForm.avator = data.data.headUrl;
            this.memberForm.name = data.data.name;
            this.memberForm.username = data.data.username;
            this.memberForm.phone = data.data.phone;
            this.memberForm.depart = this.deepTreeData(data.data.depId, this.tree).map(item => item.id);

            this.memberForm.work = data.data.workDescribe;
            this.memberForm.status = data.data.checkStatus == 0;
            this.memberForm.power = data.data.roleIds;
          }
        })
    },
    // 深层递归返回选中的父级id
    deepTreeData(id, list) {
      let nodes = [];
      let myDeep = (parentId, childlist) => {
        if (!childlist || !childlist.length) return;
        childlist.forEach(child => {
          if (child.id == parentId) {
            nodes.unshift(child);
            myDeep(child.parentId, list);
          } else {
            if (child.children && child.children.length) {
              myDeep(parentId, child.children);
            }
          }
        })
      }

      myDeep(id, list);
      return nodes;
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .my_uploader {
  display: inline-block;
}
</style>
